package com.binance.sysconf.service;

import com.rabbitmq.client.Channel;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.util.StringUtils;

import java.io.IOException;

/**
 * Description: 系统变量变更消息接收,Rabbitmq相关对象spring会自动配置
 *
 * @author hongchaoMao - Date 2018/7/24
 */
public class SysVarChangeReceiver {

    private static Log log = LogFactory.getLog(SysVarChangeReceiver.class);

    private SysConfigVarCacheService sysConfigVarCacheService;

    public void setSysConfigVarCacheService(SysConfigVarCacheService sysConfigVarCacheService) {
        this.sysConfigVarCacheService = sysConfigVarCacheService;
    }

    /**
     * Discription: 处理MQ消息的监听方法.
     * 该监听方法没有指定具体的queue-name是由系统自动分配名字.'rabbitListenerContainerFactory'spring自动配置
     * @param msg     自定义Obj2JsonMessageConverter返回的消息
     * @param channel the channel 接收对应的channel对象用于手动ack
     * @param deliveryTag 消息标记
     * @author hongchaoMao - Date 2018-7-24 15:57:19
     */
    @RabbitListener(bindings = @QueueBinding(value = @Queue(durable = "false", autoDelete = "true"),
            exchange = @Exchange(value = "sys_config_refresh", type = ExchangeTypes.FANOUT)),
            containerFactory = "rabbitListenerContainerFactory")
    public void receive(String msg, @Header(AmqpHeaders.CHANNEL) Channel channel,
                        @Header(AmqpHeaders.DELIVERY_TAG) Long deliveryTag){
        try {
            if (StringUtils.isEmpty(msg)){
                log.warn("------>receive() The mq msg of received is null !");
                return;
            }
            log.info("------>receive() Receive message :" + msg);
            // 全局刷新缓存
            sysConfigVarCacheService.refresh();
        } catch (Exception e){
            log.error("------>receive() Message parsing exception :", e);
        }
        try {
            // 手动ack确认
            channel.basicAck(deliveryTag, false);
        }catch (IOException e){
                log.error("------>receive() Rabbit channel ack error :", e);
        }
    }

}
